package com.zzg.controller;

import java.sql.Timestamp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.zzg.api.master.UserService;
import com.zzg.api.slave.IncomeService;
import com.zzg.entity.master.User;
import com.zzg.entity.slave.Income;

@Controller
@RequestMapping
public class BookController {
	public static final String RESULT_SUCCESS = "success";
	public static final String RESULT_FAILED = "failed";

	@Autowired
	private UserService userService;
	@Autowired
	private IncomeService incomeService;

	@RequestMapping(value = "/init", method = { RequestMethod.GET })
	@Transactional
	public String Init(@RequestParam("name") String name, @RequestParam("amount") double amount) {
		try {
			User user = new User();
			user.setName(name);
			userService.insert(user);

			Income income = new Income();
			income.setUserId(user.getId());
			income.setAmount(amount);
			income.setOperateDate(new Timestamp(System.currentTimeMillis()));
			incomeService.insert(income);

			return RESULT_SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return RESULT_FAILED + ":" + e.getMessage();
		}
	}

	@RequestMapping(value = "/error", method = { RequestMethod.GET })
	@Transactional
	public String error(@RequestParam("name") String name, @RequestParam("amount") double amount) {
		try {
			User user = new User();
			user.setName(name);
			userService.insert(user);

			this.throwRuntimeException();
			Income income = new Income();
            income.setUserId(user.getId());
            income.setAmount(amount);
            income.setOperateDate(new Timestamp(System.currentTimeMillis()));
            incomeService.insert(income);

            return RESULT_SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return RESULT_FAILED + ":" + e.getMessage();
		}
	}

	public void throwRuntimeException() {
		throw new RuntimeException("User defined exceptions");
	}

}
